# -*- coding: UTF-8 -*-
# author:zhou date:2019/5/16
from branch.dataCheck import DataCheck
from django.http import JsonResponse
import os
import pdb
import json
from branch.models import *
from user.models import *
import logging
logger = logging.getLogger("userlog")
logger_request = logging.getLogger("django.request")
dataCheck = DataCheck()
# Create your views here.


def test(request, *args, **kwargs):
    """
    @url:
        /music/test 
    """
    # pdb.set_trace()
    # path = os.getcwd()
    # txtPath = path + "/music/chip.txt"
    # with open(txtPath, "r", encoding='UTF-8') as f:
    #     data = f.read()
    data = {
        "code": 0,
        "msg": "成功",
    }
    # pdb.set_trace()
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def newDaily(request, *args, **kwargs):
    """
        url    : /branch/newDaily/
        method : POST

    :param request:
            token: data.token,  //用户秘钥
            dailyTime:data.dailyTime,  // 活动时间
            dailyDate : data.dailyDate,  //活动日期
            position : data.position, //活动地点
            topic: data.topic,
            attention:data.attention,
            participant:data.participant, //参会人员

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    branch = ZSDYList.objects.filter(name=user).first().branch
    daily = DailyInfo.objects.create(
        branch=branch,
        dailyType=requestParam['dailyType'],
        dailyTime=requestParam['dailyTime'],
        dailyDate=requestParam['dailyDate'],
        position=requestParam['position'],
        topic=requestParam['topic'],
        attention=requestParam['attention'],
        participant=requestParam['participant'],
    )
    data = {
        "code": 0,
        "msg": "成功",
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def getDailyList(request, *args, **kwargs):
    """
        url    : /branch/getDailyList/
        method : POST

    :param request:
            token: data.token,  //用户秘钥


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'dailyList':null, // 返回的日常列表

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    userType = user.userType
    if userType == '支部管理员' or userType == '正式党员':
        branch = ZSDYList.objects.filter(name=user).first().branch
    elif userType == '预备党员':
        branch = YBDYList.objects.filter(name=user).first().branch
    elif userType == '积极分子':
        branch = JJFZList.objects.filter(name=user).first().branch
    dailies = DailyInfo.objects.filter(branch=branch).order_by('-dailyTime')
    dailyList = []
    for daily in dailies:
        dailyList.append({
            'id': daily.id,
            'dailyTime': daily.dailyTime,
            'dailyType': daily.dailyType,
            'dailyDate': daily.dailyDate,
            'position': daily.position,
            'topic': daily.topic,
            'attention': daily.attention,
            'participant': daily.participant,
            'isShow': True,
        })
    data = {
        'code': 0,
        'msg': 'success',
        'dailyList': dailyList,
    }
    # pdb.set_trace()
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def deleteDaily(request, *args, **kwargs):
    """
        url    : /branch/deleteDaily/
        method : POST

    :param request:
            token: data.token,  //用户秘钥
            dailyId


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    daily = DailyInfo.objects.filter(id=requestParam['dailyId'])
    if len(daily) == 0:
        data = {
            'code': 1,
            'msg': '报告不存在',
        }
    else:
        daily.first().delete()
        data = {
            'code': 0,
            'msg': 'success',
        }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def getContect(request, *args, **kwargs):
    """
        url    : /branch/getContect/
        method : POST

    :param request:
            token: data.token,  //用户秘钥


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'contectList':null, // 返回的日常列表

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    contectList = []
    userType = user.userType
    if userType == '支部管理员' or userType == '正式党员':
        branch = ZSDYList.objects.filter(name=user).first().branch
    elif userType == '预备党员':
        branch = YBDYList.objects.filter(name=user).first().branch
    elif userType == '积极分子':
        branch = JJFZList.objects.filter(name=user).first().branch
    jjfzs = JJFZList.objects.filter(branch=branch)
    ybdys = YBDYList.objects.filter(branch=branch)
    zsdys = ZSDYList.objects.filter(branch=branch)
    for jjfz in jjfzs:
        contect = jjfz.name
        contectList.append({
            'id': contect.id,
            'name': contect.name,
            'headimgurl': contect.headimgurl,
            'phone': contect.phone,
            'userType': contect.userType,
            'classNum': contect.classNum,
            'isShow': True,
        })
    for ybdy in ybdys:
        contect = ybdy.name
        contectList.append({
            'id': contect.id,
            'name': contect.name,
            'headimgurl': contect.headimgurl,
            'phone': contect.phone,
            'userType': contect.userType,
            'isShow': True,
            'classNum': contect.classNum,
        })
    for zsdy in zsdys:
        contect = zsdy.name
        contectList.append({
            'id': contect.id,
            'name': contect.name,
            'headimgurl': contect.headimgurl,
            'phone': contect.phone,
            'userType': contect.userType,
            'isShow': True,
            'classNum': contect.classNum,
        })
    contectList.sort(key=lambda x: x['name'], reverse=True)
    data = {
        'code': 0,
        'msg': 'success',
        'contectList': contectList,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def saveArticle(request, *args, **kwargs):
    """
        url    : /branch/saveArticle/
        method : POST

    :param request:
            token: data.token,  //用户秘钥


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    article = ArticleInfo.objects.create(
        articleTopic=requestParam['articleTopic'],
        title=requestParam['title'],
        imgsrc=requestParam['imgsrc'],
        txtsrc=requestParam['txtsrc'],
        preview=requestParam['preview'],
    )
    data = {
        'code': 0,
        'msg': 'success',
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def getArticle(request, *args, **kwargs):
    """
        url    : /branch/getArticle/
        method : POST

    :param request:
                articleType: data.articleType,  //文章类型



    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'articleList':null, // 返回需要的文章

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    articleType = requestParam['articleType']
    articles = ArticleInfo.objects.filter(articleTopic=articleType)
    articleList = []
    for article in articles:
        articleList.append({
            'title': article.title,
            'imgsrc': article.imgsrc,
            'txtsrc': article.txtsrc,
            'preview': article.preview,
            'id': article.id
        })
    data = {
        'code': 0,
        'msg': 'success',
        'articleList': articleList,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def submitThink(request, *args, **kwargs):
    """
        url    : /branch/submitThink/
        method : POST

    :param request:
            token: data.token,  //用户秘钥
            content  内容


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    daily = DailyInfo.objects.filter(id=requestParam['dailyId']).first()
    think = ThinkInfo.objects.filter(author=user, daily=daily)
    # pdb.set_trace()
    if len(think) == 0:
        think = ThinkInfo.objects.create(
            author=user,
            daily=daily,
            content=requestParam['content']
        )
    else:
        think = think.first()
        think.content = requestParam['content']
        think.save()
    data = {
        'code': 0,
        'msg': 'success',
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def getSingleThink(request, *args, **kwargs):
    """
        url    : /branch/getSingleThink/
        method : POST

    :param request:
            token: data.token,  //用户秘钥


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
            content  内容

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    daily = DailyInfo.objects.filter(id=requestParam['dailyId']).first()
    think = ThinkInfo.objects.filter(author=user, daily=daily).first()
    content = think.content
    data = {
        'code': 0,
        'msg': 'success',
        'content': content,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def checkNotSubmit(request, *args, **kwargs):
    """
        url    : /branch/checkNotSubmit/
        method : POST

    :param request:
            dailyId:data.dailyId


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
            'memberList': null //未提交名单列表

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    dailyId = requestParam['dailyId']
    thinks = ThinkInfo.objects.filter(daily=dailyId)
    submitList = []
    for think in thinks:
        submitList.append(think.author.name)
    branch = BranchInfo.objects.filter(branch=requestParam['branch']).first()
    jjfzs = JJFZList.objects.filter(branch=branch)
    ybdys = YBDYList.objects.filter(branch=branch)
    contectList = []  # 积极分子 预备党员名单
    for jjfz in jjfzs:
        contect = jjfz.name
        contectList.append(contect.name)
    for ybdy in ybdys:
        contect = ybdy.name
        contectList.append(contect.name)
    memberList=list(set(contectList)^set(submitList))
    data = {
        'code': 0,
        'msg': 'success',
        'memberList': memberList,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def getThinks(request, *args, **kwargs):
    """
        url    : /branch/getThinks/
        method : POST

    :param request:
            dailyId:data.dailyId


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
            'memberList': null //未提交名单列表

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    dailyId = requestParam['dailyId']
    thinks = ThinkInfo.objects.filter(daily=dailyId)
    Thinks = ''
    for think in thinks:
        strings = think.author.name+'：\n'+ think.content +'\n\n'
        Thinks += strings
    data = {
        'code': 0,
        'msg': 'success',
        'thinks': Thinks,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})

def saveTest(request, *args, **kwargs):
    """
        url    : /branch/saveTest/
        method : POST

    :param request:
            dailyId:data.dailyId


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
            'memberList': null //未提交名单列表

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    question = requestParam['question']
    answer = requestParam['answer']
    test = QuestionInfo.objects.create(
        answer=answer,
        question=question,
    )
    data = {
        'code': 0,
        'msg': 'success',
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def getTest(request, *args, **kwargs):
    """
        url    : /branch/getTest/
        method : POST

    :param request:
            token: data.token,  //用户秘钥


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'testList':null, // 

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    testList = []
    tests = QuestionInfo.objects.all()
    for test in tests:
        testList.append({
            'question':test.question,
            'answer':test.answer,
            'id':test.id,
            'isShow':True,
        })
    data = {
        'code': 0,
        'msg': 'success',
        'testList':testList,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})
